{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "264df8fd",
   "metadata": {},
   "source": [
    "| 公司类型 | 修正PE   | ROE(%) | 市赚率（PE/ROE） | 特点          |\n",
    "| ---- | ------ | ------ | ----------- | ----------- |\n",
    "| 成长型  | 20\\~50 | 10\\~25 | 1.0\\~2.5    | 高成长、高波动     |\n",
    "| 稳健型  | 15\\~25 | 15\\~20 | 0.8\\~1.5    | 稳定盈利        |\n",
    "| 价值型  | 5\\~15  | 5\\~15  | 0.5\\~1.5    | 盈利低、现金流稳定   |\n",
    "| 周期性  | 10\\~20 | 5\\~15  | 0.7\\~2.0    | 盈利波动大，需结合周期 |\n",
    "| 蓝筹   | 10\\~20 | 10\\~20 | 0.7\\~1.5    | 稳定、低增长      |\n",
    "\n",
    "| 指标      | 优秀   | 合理       | 略高估      | 高估   |\n",
    "| ------- | ---- | -------- | -------- | ---- |\n",
    "| 修正PE    | <10  | 10\\~20   | 20\\~30   | >30  |\n",
    "| ROE (%) | >20  | 10\\~20   | 5\\~10    | <5   |\n",
    "| 市赚率     | <1.0 | 1.0\\~2.0 | 2.0\\~3.0 | >3.0 |\n",
    "\n",
    "\n",
    "pe = (总市值 - 账面现金) / 利润\n",
    "\n",
    "市赚率 = pe / roe\n",
    "\n",
    "上面现金这里指的是货币资金"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "82b3ac79",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== 扣非净利润及TTM预测（含 ROE & 市赚率） ===\n",
      "0. 总市值: 328.84亿\n",
      "0. 货币资金: 46.33亿\n",
      "1. 当前Q2净利润: 4.08亿\n",
      "2. 当前Q2扣非净利润: 3.92亿\n",
      "3. 当前TTM净利润: 16.49亿\n",
      "4. 当前TTM扣非净利润: 16.13亿\n",
      "5. 当前TTM净利润 ROE: 28.79%\n",
      "6. 当前TTM扣非净利润 ROE: 28.16%\n",
      "7. PE（总市值减去货币资金328.842736 - 46.330000 / 扣非TTM净利润）: 17.51\n",
      "8. 市赚率: 0.62\n"
     ]
    }
   ],
   "source": [
    "import akshare as ak\n",
    "import pandas as pd\n",
    "\n",
    "stock_code = \"603605\"\n",
    "\n",
    "def parse_amount(x):\n",
    "    if pd.isna(x):\n",
    "        return 0\n",
    "    if isinstance(x, (int, float)):\n",
    "        return x\n",
    "    x = str(x).replace(\",\", \"\").strip()\n",
    "    sign = -1 if x.startswith(\"-\") else 1\n",
    "    x = x.lstrip(\"+-\")\n",
    "    if \"亿\" in x:\n",
    "        return sign * float(x.replace(\"亿\", \"\")) * 1e8\n",
    "    elif \"万\" in x:\n",
    "        return sign * float(x.replace(\"万\", \"\")) * 1e4\n",
    "    elif x == \"\":\n",
    "        return 0\n",
    "    else:\n",
    "        try:\n",
    "            return sign * float(x)\n",
    "        except:\n",
    "            return 0\n",
    "\n",
    "def to_chinese_amount(x):\n",
    "    if x >= 1e8:\n",
    "        return f\"{x/1e8:.2f}亿\"\n",
    "    elif x >= 1e4:\n",
    "        return f\"{x/1e4:.2f}万\"\n",
    "    else:\n",
    "        return f\"{x:.2f}\"\n",
    "\n",
    "def to_percent(x):\n",
    "    return f\"{x*100:.2f}%\"\n",
    "\n",
    "# ---------------------------\n",
    "# 判断季度\n",
    "# ---------------------------\n",
    "def get_quarter_label(date):\n",
    "    month = date.month\n",
    "    if month in [1, 2, 3]:\n",
    "        return \"Q1\"\n",
    "    elif month in [4, 5, 6]:\n",
    "        return \"Q2\"\n",
    "    elif month in [7, 8, 9]:\n",
    "        return \"Q3\"\n",
    "    else:\n",
    "        return \"Q4\"\n",
    "\n",
    "# ---------------------------\n",
    "# 获取利润表（按单季度）\n",
    "# ---------------------------\n",
    "profit_df = ak.stock_financial_abstract_ths(symbol=stock_code, indicator=\"按单季度\")\n",
    "profit_df['扣非净利润'] = profit_df['扣非净利润'].apply(parse_amount)\n",
    "profit_df['净利润'] = profit_df['净利润'].apply(parse_amount)\n",
    "profit_df['报告期'] = pd.to_datetime(profit_df['报告期'])\n",
    "profit_df = profit_df.sort_values(\"报告期\", ascending=False).reset_index(drop=True)\n",
    "\n",
    "# 当前季度\n",
    "current_quarter = profit_df.loc[0]\n",
    "last_year_quarter = profit_df[profit_df['报告期'].dt.month == current_quarter['报告期'].month].iloc[1]\n",
    "current_quarter_label = get_quarter_label(current_quarter['报告期'])\n",
    "\n",
    "# ---------------------------\n",
    "# 当前季度同比增长率（小数形式）\n",
    "# ---------------------------\n",
    "profit_yoy = (current_quarter['净利润'] - last_year_quarter['净利润']) / last_year_quarter['净利润'] if last_year_quarter['净利润'] != 0 else 0\n",
    "profit_deducted_yoy = (current_quarter['扣非净利润'] - last_year_quarter['扣非净利润']) / last_year_quarter['扣非净利润'] if last_year_quarter['扣非净利润'] != 0 else 0\n",
    "\n",
    "# ---------------------------\n",
    "# 当前TTM净利润和扣非净利润（最近4季度累计）\n",
    "# ---------------------------\n",
    "ttm_profit = profit_df.head(4)['净利润'].sum()\n",
    "ttm_profit_deducted = profit_df.head(4)['扣非净利润'].sum()\n",
    "\n",
    "# ---------------------------\n",
    "# 获取资产负债表净资产及货币资金\n",
    "# ---------------------------\n",
    "debt_df = ak.stock_financial_debt_ths(symbol=stock_code, indicator=\"按报告期\")\n",
    "debt_df['归属于母公司所有者权益合计'] = debt_df['归属于母公司所有者权益合计'].apply(parse_amount)\n",
    "debt_df['货币资金'] = debt_df['货币资金'].apply(parse_amount)\n",
    "debt_df['报告期'] = pd.to_datetime(debt_df['报告期'])\n",
    "debt_df = debt_df.sort_values(\"报告期\", ascending=False).reset_index(drop=True)\n",
    "\n",
    "net_asset = debt_df.loc[0, '归属于母公司所有者权益合计']  # 最新净资产\n",
    "cash = debt_df.loc[0, '货币资金']  # 最新货币资金\n",
    "\n",
    "# ---------------------------\n",
    "# 计算 ROE(TTM)（小数形式）\n",
    "# ---------------------------\n",
    "roe_ttm = ttm_profit / net_asset if net_asset != 0 else 0\n",
    "roe_deducted_ttm = ttm_profit_deducted / net_asset if net_asset != 0 else 0\n",
    "\n",
    "# ---------------------------\n",
    "# 获取总市值\n",
    "# ---------------------------\n",
    "stock_value_em_df = ak.stock_value_em(symbol=stock_code)\n",
    "total_market_value = parse_amount(stock_value_em_df.tail(1)['总市值'].iloc[0])\n",
    "\n",
    "\n",
    "# ---------------------------\n",
    "# 计算 PE 和市赚率（小数形式）\n",
    "# ---------------------------\n",
    "pe = (total_market_value - cash) / ttm_profit_deducted if ttm_profit_deducted != 0 else 0\n",
    "market_earnings_ratio = pe / 100 / roe_deducted_ttm if roe_deducted_ttm != 0 else 0\n",
    "\n",
    "# ---------------------------\n",
    "# 打印结果\n",
    "# ---------------------------\n",
    "print(\"=== 扣非净利润及TTM预测（含 ROE & 市赚率） ===\")\n",
    "print(f\"0. 总市值: {to_chinese_amount(total_market_value)}\")\n",
    "print(f\"0. 货币资金: {to_chinese_amount(cash)}\")\n",
    "print(f\"1. 当前{current_quarter_label}净利润: {to_chinese_amount(current_quarter['净利润'])}\")\n",
    "print(f\"2. 当前{current_quarter_label}扣非净利润: {to_chinese_amount(current_quarter['扣非净利润'])}\")\n",
    "print(f\"3. 当前TTM净利润: {to_chinese_amount(ttm_profit)}\")\n",
    "print(f\"4. 当前TTM扣非净利润: {to_chinese_amount(ttm_profit_deducted)}\")\n",
    "print(f\"5. 当前TTM净利润 ROE: {to_percent(roe_ttm)}\")\n",
    "print(f\"6. 当前TTM扣非净利润 ROE: {to_percent(roe_deducted_ttm)}\")\n",
    "print(f\"7. PE（总市值减去货币资金{(total_market_value / 10000 / 10000):2f} - {(cash / 10000 / 10000):2f} / 扣非TTM净利润）: {pe:.2f}\")\n",
    "print(f\"8. 市赚率: {market_earnings_ratio:.2f}\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
